package day12.xml;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Demo {

    //创建一个文档出去
    @Test
    public void test() throws IOException {
        //1 利用DocumentHelper类创建Document
        Document doc = DocumentHelper.createDocument();

        //添加注释
        doc.addComment("this is a create xml test!");
        Element rootEle = doc.addElement("note");
        //2 doc添加元素
        Element toEle = rootEle.addElement("to");

        //添加属性
        toEle.addAttribute("id", "1");

        //3 元素设置文本或属性
        toEle.setText("林志玲");

        rootEle.addElement("from").setText("周杰伦");
        rootEle.addElement("title").setText("今晚有空吗");
        rootEle.addElement("heading").setText("一起吃个饭");

        //4 利用IO流OutputStream类
        OutputStream os = new FileOutputStream("note.xml");
        //5 write(文档)
        //XMLWriter writer = new XMLWriter(os);//默认格式

        //带格式的输出xml
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");
    }

    @Test
    public void test2() throws IOException, Exception {
        //读取note.xml
        InputStream is = new FileInputStream("note.xml");
        //创建解析对象
        SAXReader reader = new SAXReader();
        //读取输入流返回文档
        Document doc = reader.read(is);
        //解析to元素
        Element toEle = doc.getRootElement().element("to");
        //改为周杰伦的妻子
        toEle.setText("Hannah");

        //4 利用IO流OutputStream类
        OutputStream os = new FileOutputStream("note.xml");
        //5 write(文档)
        //XMLWriter writer = new XMLWriter(os);//默认格式

        //带格式的输出xml
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");

    }

    @Test
    public void test3() throws Exception{
        //读取note.xml
        InputStream is = new FileInputStream("note.xml");
        //创建解析对象
        SAXReader reader = new SAXReader();
        //读取输入流返回文档
        Document doc = reader.read(is);
        doc.remove(doc.getRootElement().element("to"));
        //解析to元素
        Element toEle = doc.getRootElement().element("to");
        //改为周杰伦的妻子
        toEle.detach();
//        toEle.setText("Hannah");
        OutputStream os = new FileOutputStream("note.xml");
        XMLWriter writer = new XMLWriter(os, OutputFormat.createPrettyPrint());
        writer.write(doc);

        System.out.println("文档写好了...");
    }
}